package com.example.micro_benchmark_markdown

import androidx.benchmark.Arguments
import androidx.benchmark.IsolationActivity
import androidx.benchmark.Shell
import androidx.benchmark.junit4.AndroidBenchmarkRunner
import androidx.test.platform.app.InstrumentationRegistry

class CustomAndroidBenchmarkRunner : AndroidBenchmarkRunner() {
    override fun waitForActivitiesToComplete() {
        // IsolationActivity may lazily use UiAutomation to access [CpuInfo.locked] on the UI
        // thread, which on some platform versions (observed locally and in CI on API 26) can cause
        // UiAutomation to fail to connect if that's the first use. To prevent that, initialize
        // here, before the main thread. See also b/193064052
        Shell.connectUiAutomation()

        // We don't call the super method here, since we have
        // an activity we intend to persist between tests

        // Before/After each test, from the test thread, synchronously launch
        // our IsolationActivity if it's not already resumed
        var isResumed = false
        runOnMainSync {
            isResumed = IsolationActivity.resumed
        }
        // dryRunMode doesn't care about isolation or sustained perf mode, so skip launch cost
        if (!isResumed && !Arguments.dryRunMode) {
//            IsolationActivity.launchSingleton()
            val instrumentation = InstrumentationRegistry.getInstrumentation()
            val packageName =
                instrumentation.targetContext.packageName
            val activity = IsolationActivity::class.java.name
            instrumentation.uiAutomation.executeShellCommand("am start -n $packageName/$activity")
            Thread.sleep(1000)
        }

    }
}